package com.coisini.controller.user;

import com.coisini.entity.Dish;
import com.coisini.result.Result;
import com.coisini.service.DishService;
import com.coisini.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.DataValidation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
@Api(tags = "C端-菜品 浏览接口")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据分类id查询菜品
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<DishVO>> getByCategoryId(@RequestParam Long categoryId){
        log.info("根据分类id查询菜品:{}",categoryId);
        //利用Reids进行缓存  注：存取一致
        //1.判断是否有缓存
        String key="dish_" +categoryId;
        List<DishVO> list= (List<DishVO>) redisTemplate.opsForValue().get(key);
        if (list != null && list.size() > 0){
            //2.有缓存直接返回数据
            return Result.success(list);
        }
        //3.没有缓存，调用数据库查询，然后写入缓存
        list= dishService.listWithFlavor(categoryId);
        redisTemplate.opsForValue().set(key,list);
        return Result.success(list);
    }
}
